<?php
namespace Index\Controller;
use Think\Controller;
use Org\Util\Wechat;
header("Content-type: text/html; charset=utf-8"); 
class AdministratorController extends Controller {
    public $wx = null; 
    
    public function _initialize(){  
        $this->wx = new Wechat(C('options'));
    }
    public function index(){
        $openid = session('openid');
        if(empty($openid)){
            $this->redirect('wlg');
        }
        //验证签名
        $arr=$this->check_form();
        //服务中心列表
        $list=M('sc')->select();      
        //调用微信jssdk获取签名等
        $weObj = new \Org\Util\Wechat(C('options'));
        //获取签名
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $sign = $weObj->getJsSign($url);

        //小区列表
        $apts = M('apt')->select();

        //P($sign);
        $this->assign('sign',$sign);
        $this->assign('list',$list);
        $this->assign('apts',$apts);
        $this->assign('res',$openid);
        $this->assign('arr',$arr);
        $this->display('index');
    }
    function wlg(){ 
        $callback = 'http://sunwayuchoice.com/index.php/Administrator/lgback';
        $url = $this->wx->getOauthRedirect($callback);
        header('location:'.$url);
    }
    
    function lgback(){ 
        $tk = $this->wx->getOauthAccessToken();
        session('openid',$tk['openid']);
        $this->redirect('index');
    }

	/*public function code(){
		$REDIRECT_URI='http://sunwayuchoice.com/index.php/Administrator/index';
		$scope='snsapi_base'; //静默授权 关注用户默认的权限
		//$scope='snsapi_userinfo'; //用户点击授权  未关注也可以获取
		$url='http://open.weixin.qq.com/connect/oauth2/authorize?appid='.C('APPID').'&redirect_uri='.urlencode($REDIRECT_URI).'&response_type=code&scope='.$scope.'&state=123#wechat_redirect';
		$recode= file_get_contents($url);
		header("Location:".$url);
	}*/

	//表单令牌短信验证防止重复提交
	public function check_form(){
    	session("token",md5(rand(10000,99999)));
    	$check=session("token");
    	return $check;
    }
	
    
    //发送短信
    public function msg()
    {   
        $num=$this->randString();
        $phone=trim(I('phone'));
      
        $list=M('rbac_manager')->where('phone="'.$phone.'"')->find();
        if (!empty($list)) {
        	$this->ajaxReturn(array('s'=>'no','m'=>"手机号已经被注册"));
        }

        $check_phone=M('old_manager')->where('phone="'.$phone.'"')->find();
        if (empty($check_phone)) {
            $this->ajaxReturn(array('s'=>'no_m','m'=>"抱歉,您不是管理员"));
        }    
        //表单令牌验证
        $token=I('token');
        if ($token!=session('token') || empty($token)){
    		// 令牌验证错误
    		$this->ajaxReturn(array('s'=>"check",'m'=>"令牌验证错误"));
		}else{
        //正则验证手机号
        if(preg_match("/^1[34578]{1}\d{9}$/",$phone)){  
	        $c=Vendor('Alidayu.top.TopClient'); 
	        $c=new \TopClient();
	        $c->appkey =C('AlidayuAppKey');
	        $c->secretKey =C('AlidayuAppSecret');
	        $req=Vendor('Alidayu.top.request.AlibabaAliqinFcSmsNumSendRequest');
	        $req=new \AlibabaAliqinFcSmsNumSendRequest();
	        $req->setSmsType("normal");
	        $req->setSmsFreeSignName("注册验证");
	        $req->setSmsParam("{\"code\":\"$num\",\"product\":\"尚元优家Uchoice\"}");
	        $req->setRecNum($phone);
	        $req->setSmsTemplateCode("SMS_12200894");
	        $resp = $c->execute($req);
			S($phone,$num,120);
			$this->ajaxReturn(array('s'=>'ok','m'=>"发送成功"));
        }else{  
        	$this->ajaxReturn(array('s'=>"fail",'m'=>"令牌验证错误"));
		}  
     }
	}
    /**
     * 获取随机位数数字
     * @param  integer $len 长度
     * @return string       
     */
    protected static function randString($len = 4)
    {
        $chars = str_repeat('0123456789', $len);
        $chars = str_shuffle($chars);
        $str   = substr($chars, 0, $len);
        return $str;
    }


    //验证短信验证码
    public function check(){//exit("qqq");
            $openid =I('openid');
            if (empty($openid)) {
                $this->ajaxReturn(array('c'=>"openid",'m'=>"出现错误,请点击注册链接重新进行注册"));
            }
	        $num=I('num');
	        $phone = I('phone');


	        $verify = S($phone);
	        if (empty($verify)) {
	            //exit('验证码失效');
	            $this->ajaxReturn(array('c'=>"shixiao",'m'=>"验证码失效"));
	        }
	        if ($verify != $num) {
	            //echo '验证失败';
	            $this->ajaxReturn(array('c'=>"error",'m'=>"验证码错误"));
	        }else{
	           $this->ajaxReturn(array('c'=>"yes",'m'=>"验证成功"));
	        }
    }
    //管理员用户注册
    public function register(){
        $phone=trim(I('phone'));
       
       	$openid=I('openid');
    	$sc_id=trim(I('plot'));
        $name=trim(I('name'));
    	$sex=trim(I('sex'));
        $password=md5(trim(I('password')));
        //实例化表
        $Manager=M('rbac_manager');
    	$list=$Manager->where('phone="'.$phone.'"')->find();
    	if (!empty($list)) {
    		error('您已经是管理员了，请进行登录',$_SERVER['HTTP_REFERER']);
    	}
    	
    	$data = array(
    		'phone' => $phone, 
    		'openid'=>$openid,
            'username' => $name,
    		'sex' => $sex, 
    		'ctime'=>time(),
            'password' => $password,
            'sc'=>$sc_id,
		);
        //P($data);
        //插入管理员表
    	$res_add=$Manager->data($data)->add();
        
    	if (false !== $res_add) {
            // 加入用户表 socket聊天功能需要
            $customerModel = M('customer');
            $customerHas = $customerModel->where(['phone'=>$phone])->find();
            if(empty($customerHas)){
                $aptid=trim(I('aptid'));
                $customerData = array(
                    'phone' => $phone, 
                    'openid'=> $openid,
                    'plot'  => $aptid, 
                    'name'  => $name,
                    'sex'   => $sex, 
                    'ctime' => time(),
                    'mtime' => time(),
                    'pwd'   => $password,
                );
                $aptInfo=M('apt')->where(['id'=>$aptid])->find();
                if($aptInfo){
                    $customerData['sc'] = $aptInfo['sid'];
                }
                //判断是否是老用户
                $list_old = M('old_customer')->where(['phone'=>$phone])->find();
                if(!empty($list_old)){
                    $customerData['num'] = $list_old['num'];
                    $customerData['email'] = $list_old['email'];
                    $customerData['status_customer'] = 2;
                }
                $customerModel->data($customerData)->add();
            }else{
                if($customerHas['openid']!=$openid){
                    $customerModel->where(['id'=>$customerHas['id']])->save(['openid'=>$openid]);
                }
            }

            //插入管理员所属组的表
    		$v= array(
                'role_id'=>4,
                'user_id'=>$res_add,
            );
            $res = M('rbac_role_manager')->data($v)->add();
            if (false==$res) {
                $this->ajaxReturn(array('s'=>1,'m'=>"再试一次咯"));
                echo '再试一次咯';exit;
            }

            $arr = array(
               'sc_id' => $sc_id,
               'user_id'=> $res_add,
             );
            //插入服务中心的表
            $result=M('sc_manager')->data($arr)->add();
            if (false !== $result) {
                $this->ajaxReturn(array('s'=>1,'m'=>"恭喜"));
                echo "恭喜";
            }else{
                $this->ajaxReturn(array('s'=>0,'m'=>"再试一次咯"));
                echo '再试一次咯';exit;
            }
    	}else{
            $this->ajaxReturn(array('s'=>0,'m'=>"再试一次咯"));
    		echo '再试一次咯';exit;
    	}

    }

}
?>